<template>
    <div class="boxContentCss">
            <EdCreateCard :title="isUpdate ? '编辑设备信息' : '新增设备'">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <el-form class="width-m25" :model="form" :rules="rules" ref="ruleForm" label-position='right' label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item class="width-m25" label="项目名称" prop="villageId" :rules="$validate.validates({required:true,msg:'请选择项目名称'})">
                            <EdSelect v-model="form.villageId" ref="select" :selectParams="villageNameParams" style="width:100%"></EdSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item class="width-m25"  label="设备编号" prop="equipmentNo" :rules="$validate.validates({required:true,msg:'请选择巡检类型'})">
                            <el-input class="flex-input"  disabled v-model="form.equipmentNo" placeholder="请输入设备编号"></el-input>
                            <!-- <EdSelect v-model="form.equipmentNo" :selectParams="equipmentNoParams" style="width:100%"></EdSelect> -->
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item class="width-m25"  label="设备名称" prop="equipmentName" :rules="$validate.validates({required:true,msg:'请选择设备名称'})">
                                <el-input class="flex-input"  v-model="form.equipmentName" placeholder="请输入设备名称" maxlength="50"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item class="width-m25"  label="设备标识" prop="isImportant" :rules="$validate.validates({required:true,msg:'请选择是否为重要设备'})">
                                <template>
                                    <el-radio v-model="form.isImportant" label='0'>重要设备</el-radio>
                                    <el-radio v-model="form.isImportant" label='1'>普通设备</el-radio>
                                </template>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item class="width-m25" label="设备类型" prop="equipmentType" :rules="$validate.validates({required:true,msg:'请选择巡检类型'})">
                            <EdSelect v-model="form.equipmentType" :selectParams="equipmentTypeParams" style="width:100%" :formatter="setDicType"></EdSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item class="width-m25"  label="安装位置" prop="installationSite" :rules="$validate.validates({required:true,msg:'请选择输入安装位置'})">
                                <el-input class="flex-input"  v-model="form.installationSite" placeholder="请输入安装位置" maxlength="100"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item class="width-m25"  label="设备清单" prop="inventoryName">
                                <el-input class="flex-input" disabled v-model="form.inventoryName" placeholder="请上传设备清单"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-upload
                            :action="action"
                            :headers="headers"
                            :on-remove="handleRemove"
                            :before-remove="beforeRemove"
                            :on-success="uploadSuccess"
                             :before-upload="beforeUploadChange"
                            multiple
                            :limit="1"
                            :on-exceed="handleExceed"
                            :file-list="fileList">
                            <el-button  class="ed-button ed_black-bottom">浏览</el-button>
                        </el-upload>
                    </el-row> 
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item class="width-m25"  label="售后服务电话" prop="supportPhone">
                                <el-input class="flex-input"  v-model="form.supportPhone" placeholder="请输入手机号或者座机号，座机号用-连接"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <div class="projectButton" >
                        <el-button type="info" @click="submit()" class="ed-button ed_black-bottom" >提&nbsp;&nbsp;交</el-button>
                        <el-button @click="$utilsSet.goBack($router),dialogVisible = false" icon-class="back" class="ed-button ed_white_bottom">取&nbsp;&nbsp;消</el-button>
                    </div>
                </el-form>    
            </EdCreateCard>
    </div>
</template>
<script>
    import EdDialog from 'src/components/EdDialog.vue'
    import EdSelect from 'src/components/EdSelect.vue' 
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import { defineComponent } from 'vue'
    import {deviceEdit, deviceAdd,projectList,deviceDetail} from "./api.js";
    import {getToken} from 'src/utils/auth'
    import {getDictByCode} from "src/api/dictionaries";
    export default defineComponent({
        name: "projectCreate",
        components: { EdCreateCard,EdSelect,EdDialog},
        data(){
            const validatePhone = (rule,value,callback) => {
                if(value){
                    if (/^1/.test(value)) {
                        if ( /^1[3|4|5|7|8][0-9]\d{8}$/.test(value)) {
                            callback();
                        } else {
                            callback(new Error( "请输入正确的11位的手机号"))
                        }
                    } else if (/^0/.test(value)) {
                        if (/^0\d{2,4}-\d{6,9}$/.test(value)) {
                            callback();
                        } else {
                            callback(new Error("请用0xxx-xxxxxxx格式"))
                        }
                    }else{
                        callback(new Error("请输入11位手机号或0xxx-xxxxxxx格式座机号"))
                    }
                 }else {
                    callback();
                }
            }
            return{
                rules:{
                    supportPhone: [
                        { validator: validatePhone,trigger: 'blur' }
                    ]
                },
                form:{
                    equipmentName: "",
                    equipmentNo: "",
                    equipmentType: '',
                    installationSite: "",
                    supportPhone: "",
                    isImportant:'',
                    villageName: "",
                    villageId:'',
                    facilityInventory:'',
                    inventoryName:''
                },
                villageNameParams:{
                    placeholder:"请选择项目名称",
                    options: [],
                    props: {label:"label", value:"value"},
                    disabled:false
                },
                equipmentTypeParams:{
                    placeholder:"请选择",
                    options: [],
                },
                showChoosePoint:false,
                isIndeterminate:false,
                checkAll:false,
                tableData: [],
                multipleSelection: [],
                isUpdate:false,
                
                action:"",
                headers:{
                    RdAuthorization: getToken()
                },
                fileList: [],
            }
        },
        watch:{
            fileList: {
                deep: true,
                immediate: true,
                handler(newVal, oldVal) {
                    this.form.facilityInventory = String(newVal.map(item => item.path))
                    this.form.inventoryName = String(newVal.map(item => item.name))
                }
            },
            
        },
        activated(){
             this.initDic()
             this.action = this.$baseApi + "/file/upload"
            if(this.$route.query.id){
                this.isUpdate=true;
                this.villageNameParams.disabled = true
                this.$refs.select.disabled = true
                this.deviceDetail()
            }else {
                this.form.equipmentNo = this.genID(10)
                this.isUpdate = false
                this.villageNameParams.disabled = false
                this.$refs.select.disabled = false
            }
            // 获取字典值方式
            getDictByCode("deviceType").then(response => {
                if(response.success) {
                    this.equipmentTypeParams.options=response.data.items
                }
            })
        },
        deactivated() {
            this.form={
                equipmentName: "",
                equipmentNo: "",
                equipmentType: '',
                installationSite: "",
                supportPhone: "",
                isImportant:'',
                villageName: "",
                villageId:'',
                facilityInventory:'',
                inventoryName:''
                }
           this.fileList= []
           this.$refs.ruleForm.resetFields()
        },
        methods:{
            // 根据id查详情的接口
            deviceDetail(){
                deviceDetail({id:this.$route.query.id}).then(response => {
                    if(response.success) {
                        this.form = {...response.data}
                        this.form.equipmentType=response.data.equipmentType.toString()
                        this.form.isImportant=response.data.isImportant.toString()
                        this.form.villageId = response.data.villageId.toString()
                    }
                })
            },
            initDic(){
                projectList({page:1,pageSize:999999}).then(response => {
                    if(response.success) {
                        let options = response.data.records.map(x=>{return {label:x.villageName,value:x.villageId}})
                        this.villageNameParams.options=options
                    }
                })
            },
            setDicType(row ,cloumn) {
            let options = this.equipmentTypeParams.options.find(x => x.value == row.equipmentType)
            return options.label
            }, 
            selectPoint(){
                this.showChoosePoint=true
            },
            closeDialog(){
                this.showChoosePoint=false
            },
            saveDialog(){
                this.showChoosePoint=false
            },
            handleCheckAllChange(){
              this.isIndeterminate = false
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleRemove(file, fileList) {
                // 1.获取将要删除图片的临时路径
                const filePath = file.name;
                // 2.从pics数组中，找到图片对应的索引值
                const i = this.fileList.findIndex((x) => x.name === filePath);
                // 3.调用splice方法，移除图片信息
                this.fileList.splice(i, 1);
            },
            // handlePreview(file) {
            //     console.log(file)
            //     this.fileList.push(file)
            // },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            beforeRemove(file, fileList) {
                let name_1 = '', len = file.name.length;
                if(len > 50){
                    name_1 = '文件名不超过50个字符，'
                } else {
                    name_1 = ''
                }
                return this.$confirm(`${name_1}确定移除 ${ file.name }？`, '提示', {
                    showCancelButton: len > 50 ? false : true,
                    // type: 'warning',
                    // center: true
                });
            },
            uploadSuccess(response,file, fileList){
                // console.log('+++response','file');
                this.form.inventoryName=file.name
                this.form.facilityInventory = response.data
            },
            beforeUploadChange(file){
                const isLt2M = file.name.length <= 50;
                if (!isLt2M) {
                    // this.$message.error('文件名不能超过50个字符');
                }
                return isLt2M;
            },
            submit(){
                this.$refs['ruleForm'].validate((valid)=>{
                    if(!valid){
                        return
                    }
                    // 先判断是不是编辑按钮，如果是就调下面编辑的api
                    if(this.isUpdate){
                        deviceEdit(this.form).then(response => {
                            if(response.success) {
                                this.$message.success({
                                    message: '编辑成功！',
                                    duration: 2000,
                                    center:true
                                });
                                this.$router.back()
                            }
                        })
                    } else {
                        this.villageNameParams.options.forEach((v, i)=>{
                            if(this.form.villageId==v.value){
                                this.form.villageName=v.label
                            }
                        })
                        deviceAdd(this.form).then(response => {
                            if(response.success) {
                                this.$message.success({
                                    message: '新增设备成功！',
                                    duration: 2000,
                                    center:true
                                });
                                this.$router.back()
                                
                            }
                        })
                    }
                })
            },
            genID(length){
            return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36);
            }
        },
        
    })
</script>
<style scoped>
.el-message-box .el-message-box__message p{
    word-wrap: break-word !important;
}
</style>
<style lang="scss" scoped>
.boxContentCss{
    position: relative;
    padding-bottom: 150px;
    .el-form{
        padding: 45px 45px 15px 15px;
    }
}
.projectButton{
    flex: 1;
    display: flex;
    justify-content: flex-start;
    margin-left: 120px;
}
.createBack{
    margin-right: 50px;
}
.time {
    .el-form-item__content {
        margin-left: 10px
    }
}
.checkboxPoint{
    display: flex;
    justify-content: space-between;
}
:deep .el-table .el-table__body-wrapper{
    &::-webkit-scrollbar-thumb{
        background-color: #C1C1C1;
        border-radius: 2px;
    }
}
.scrollbar {
    height: 150px;
    border: 1px solid #DCDFE6;
    border-radius: 2px;
    padding: 0 10px;
    width: 100%;
    .item {
        display: flex;
        align-content: center;
        justify-content: space-between;
        padding: 0 4px;
        border-radius: 2px;

        &:hover {
            background-color: bisque;
        }
    }
}
:deep .el-upload-list {
    margin-left: 125px;
    width: 40%;
    padding: 10px;
}
</style>